Home:ALL Converter>Change title of Bootstrap Modal before window opens using javascript or jquery

Change title of Bootstrap Modal before window opens using javascript or jquery

Ask Time:2022-11-14T08:40:57         Author:user17195990

Json Formatter

I am working on an ASP.NET core project. I am using the same javascript function to add and edit for multiple modal forms. Each modify"obj" modal form has it's own data-target, so the correct modal will open. What I'm trying to do is change the title to Add "obj" or Edit "obj", depending on if the user is opening the Add or Edit Modal, but I can't seem to get it right.

Update I've added the viewModels. There are two other objects that use this modal. They have their own modal partial view and their own target id's, which are #modifyClient, #modifyEmployee, and #modifyEvent. But they all use the Modify Object js function.

Event Model

public class Event
{
    [Key]
    [DatabaseGenerated(DatabaseGeneratedOption.Identity)]
    public int Id { get; set; }
    [Required]
    public string EventName { get; set; }
    public string Type { get; set; }
    [Required]
    public string Location { get; set; }
    public DateTime EventDate { get; set; }
    public DateTime StartTime { get; set; }
    public DateTime EndTime { get; set; }
    public bool Food { get; set; }
    public bool Bar { get; set; }
    public int Guests { get; set; }
    public string? Notes { get; set; }
    [ForeignKey("Client")]
    public int ClientId { get; set; }
    public int? CreatedBy { get; set; }
    public DateTime? CreatedOn { get; set; } 
    public DateTime LastUpdate { get; set; } = DateTime.Now; 

EventViewModel

public class EventViewModel 
{
    public Event Event { get; set; }
    [Required]
    public string ClientName { get; set; }
}

EventListDetails

public class EventListDetails
{
    public int EventId { get; set; }
    public string EventName { get; set; }
    public DateTime EventDate { get; set; }
    public DateTime StartTime { get; set; }
    public DateTime EndTime { get; set; }
    public string Type { get; set; }
    public int ClientId { get; set; }
    public string ContactName { get; set; }
    public string Phone { get; set; }
}

This is the shared function for all of my modify modals in site.js

$(function () {
    var placeholderElement = $('#PlaceHolderHere');
    console.log(placeholderElement);
    var id;
    var controller;
    var action;
    var targetModal; //stores the id of correct modal

    //onclick from index to open modal
    $('button[data-bs-toggle="ajax-modal"]').click(function (e) {
        target = e.target;
        
        controller = $(target).data('controller');
        action = $(target).data('action');
        targetModal = $(target).data('target');
       
        //checks data-modify to determine if form is Add or Edit
        var addOrEdit = $(target).data('modify-type');
        
        if (addOrEdit == 'Edit')
        {
            id = $("#selectedId").val();
            /*document.querySelector('#modifyLabel').innerHTML = "Edit Event";*/
            /*above commented out code causes "Uncaught TypeError: Cannot set properties of 
              null, replacing querySelectior with getElementById causes the same error 
              here*/
            if (id == null || id == "") {
                alert("Please Select a Record to Edit");
                return;
            }
        }
        else
        {
            id = 0;
        }
        
        var url = "/" + controller + "/" + action + "/" + id;
        console.log(url);
        $.get(url).done(function (data) {
            //cannot find the code to attempt updating the data for title here
            placeholderElement.html(data);
            placeholderElement.find('.modal').modal('show');
        });
        
        /*this function is never reached, Also not sure if targetModel can be passed this way*/
        $(targetModal).on('show.bs.modal', function (event) {
            //if this works addOrEdit would need to be checked again before change
            $(this).find('#modifyLabel').text("Edit Event");
        });

        //this version also never reached
        //$('.modal').on('show.bs.modal', function (event) {
        //    if (addOrEdit == 'Edit') {
        //        $(this).find('h4.modal-title').text("Edit Event");
        //    }
        //});
    })

    

    //onclick to save modal form information
    placeholderElement.on('click', '[data-bs-save="modal"]', function (event) {
        event.preventDefault();
       
        //get form and form action and serialize (for Employee, Client, and Event _Modify""ModalPartials)
        var form = $(this).parents('.modal').find('form');
        var actionUrl = form.attr('action');
        var sendViewModel = form.serialize();
        alert(sendViewModel);
        
        //close modal if all fields are valid
        $.post(actionUrl, sendViewModel).done(function (data) {
            if (data === true) {
                placeholderElement.find('.modal').modal('hide');
                location.reload();
                return;
            }
            
            //replace modal with modelState errors if fields are not valid
            var newBody = $('.modal-body', data);
            placeholderElement.find('.modal-body').replaceWith(newBody);
        });
    });
});

code for modal in Event/_ModifyEventModalPartial.cshtml

@model Project.ViewModels.EventViewModel

<div class="modal modal-fade" id="modifyEvent">
    <div class="modal-dialog modal-lg">
        <div class="modal-content">
            <div class="modal-header">
                <h4 class="modal-title" id="modifyLabel">Add Event</h4>
                <button type=button class="close" data-bs-dismiss="modal">
                    <span>x</span>
                </button>
            </div>
            <div class="row">
                <p class="text text-danger" id="eventDateEditNotice"> 
                <!--html here, is also only for Edit, and needs to be added dynamically-->
                </p>
            </div>
            <form action="Event/Modify" method="Post" runat="server" autocomplete="off">
                <div class="modal-body">
                    <div class="row">
                        <span asp-validation-for="Event.EndTime" class="text-danger"></span>
                    </div>
                     <div class="row mb-3">
                        <div class="col form-group">
                            <div>
                                <label>Event Date</label>
                                <input asp-for="Event.EventDate" id="datepicker" type="date" /> @*value="Event.EventDate"*@
                                 
                                <span class="add-on">
                                    <i data-date-icon="icon-calendar">
                                    </i>
                                </span>
                            </div>
                        </div>
                        <div> ... //input for EventViewModel properties continues
                        </div>
                    </div>
                           
                    <div class="modal-footer">
                        <button type="button" class="btn btn-primary" data-bs-dismiss="modal">Cancel</button>
                        <button type="submit" class="btn btn-primary" id="savechanges" data-bs-save="modal">Save</button>
                    </div>
                </div>
            </form>
        </div>
    </div>
</div>
@section Scripts{
    @{await Html.RenderPartialAsync("_ValidationScriptsPartial");}
} 

Button events for opening modal "Add/Edit" and placeholder div in Event/Index.cshtlm

@model IEnumerable<EventListDetails>  

<div id="PlaceHolderHere"></div> 

<!--button to _ModifyEventModalPartial "Add" (js.ModifyObject)-->
<button type="button" class="btn btn-primary" data-bs-toggle="ajax-modal" data- 
        target="#modifyEvent" data-controller="Event" data-action="Modify" data-modify- 
        type="Add">
        Add Event
</button> 

<!--button call to _ModifyEventModalPartial "Edit" (js.ModifyObject) -->
<button class="btn btn-primary" data-bs-toggle="ajax-modal" data-target="#modifyEvent"
        data-controller="Event" data-action="Modify" data-modify-type="Edit">
        Edit
</button>  

Modify Get and Post Actions in EventController.cs

[HttpGet]
public IActionResult Modify(int id)
{
    EventViewModel viewModel = new EventViewModel();
    //add new event in modal
    if (id == 0)
    {
        viewModel.Event = new Event();
        viewModel.Event.EventDate = DateTime.Parse(DateTime.Now.ToString("MM/dd/yyyy hh:mm tt"));
        //create new viewModel properties cont...
    }
    //edit event with id in modal
    else
    {
         viewModel.Event = _db.Events.Find(id);
         //other properies cont...
    }
    return PartialView("_ModifyEventModalPartial", viewModel); ;
}

//Post: /Event/Modify/{id}
/*adds and edits and event. Code behind for ~Views/Event/_ModifyEventModalPartial. Called from site.js Modify Object Function*/
[HttpPost]
public IActionResult Modify(EventViewModel viewModel)
{
    viewModel.Event.StartTime = viewModel.Event.EventDate.Date + 
    viewModel.Event.StartTime.TimeOfDay;
    //set end time...
    if (viewModel.Event.StartTime < viewModel.Event.EndTime) 
    {
        if (ModelState.IsValid)
        {
        //add new               
        if (viewModel.Event.Id == 0)
        {
            //add new event
        }
        //if edit
        else
        {
            //edit event
        }   
        return Ok(true);  //return pass to Modify Object function in site.js
    }
    return PartialView("_ModifyEventModalPartial", viewModel);
}

I added kind of a lot of code in case anyone wanted to try reproducing the problem. but it's definitely something wrong in the site.js function, I just can't seem to figure out how to fix it.

Author:user17195990,eproduced under the CC 4.0 BY-SA copyright license with a link to the original source and this disclaimer.
Link to original article:https://stackoverflow.com/questions/74425909/change-title-of-bootstrap-modal-before-window-opens-using-javascript-or-jquery
yy